<?php

namespace App\Models\Sample;

use App\Models\BaseModel;
use Illuminate\Support\Facades\Auth;
use App\Models\Product\Product;
use App\Helpers\Code;

class SampleTypeWorkflow extends BaseModel
{

    protected $table = 'sample_type_workflows';
    protected $fillable = [
        'sample_type_id', 'workflow_id', 'product_id', 'is_default', 'created_by', 'updated_by', 'data_scope',
    ];

    public function workflow()
    {
        return $this->belongsTo('App\Models\Sample\Workflow', 'workflow_id');
    }

    public function product()
    {
        return $this->belongsTo('App\Models\Product\Product', 'product_id');
    }

    /**
     * 添加样本类型工作流
     * @param $data
     * @return mixed
     */
    public function addTypeWorkflow($data)
    {
        $sampleType = SampleType::find($data['sample_type_id']);
        $workflow = Workflow::find($data['workflow_id']);
        if (isset($data['product_id'])) {
            $product = Product::find($data['product_id']);
            if (!$product) {
                return null;
            }
        }

        if (!$sampleType || !$workflow) {
            return null;
        }

        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['data_scope'] = $this->getDataScope();
        return $this->create($data);
    }

    /**
     * 编辑样本类型工作流
     * @param $data
     * @param $id
     */
    public function editTypeWorkflow($data, $id)
    {
        $model = $this->find($id);
        if (!$model) {
            return null;
        }
        $sampleType = SampleType::find($data['sample_type_id']);
        $workflow = Workflow::find($data['workflow_id']);
        if (isset($data['product_id'])) {
            $product = Product::find($data['product_id']);
            if (!$product) {
                return Code::INSIDE_ERROR;
            }
        }

        if (!$sampleType || !$workflow) {
            return Code::INSIDE_ERROR;
        }

        $data['updated_by'] = Auth::id();
        return $model->updateOrCreate(['id' => $id], $data);
    }

    /**
     * 删除样本类型工作流
     * @param $id
     */
    public function deleteTypeWorkflow($id)
    {
        $model = $this->find($id);
        if (!$model) {
            return null;
        }

        return $model->delete();
    }

    /**
     * 获取指定样本类型下工作流
     * @param $id
     */
    public function getTypeAll($id)
    {
        $model = $this->with(['workflow:id,title,code', 'product:id,title,code'])
            ->select(['id', 'sample_type_id', 'workflow_id', 'product_id', 'is_default'])
            ->where('sample_type_id', $id)->get();
        if (!$model) {
            return null;
        }

        return $model;
    }
}
